﻿using Newtonsoft.Json;

// Code rewritten from: http://www.codeproject.com/Articles/272335/JSON-Serialization-and-Deserialization-in-ASP-NET
namespace BigDataFramework.Helpers
{
    public static class JSONHelper
    {
        /// <summary>
        /// Serializes the passed in object into a string
        /// </summary>
        /// <typeparam name="T">The type of the object to serialize</typeparam>
        /// <param name="obj">The serializable object</param>
        /// <returns>the passed in obj object as a JSON string</returns>
        public static string SerializeAsJson<T>(T obj)
        {
            if (obj == null)
                return string.Empty;

            string output = JsonConvert.SerializeObject(obj);

            return output;
        }

        public static T DeserializeFromJson<T>(string jsonString)
        {
            if (string.IsNullOrEmpty(jsonString))
                return default(T);

            T output = default(T);

            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.TypeNameHandling = TypeNameHandling.All;       //hopefully this fixes the inheritance issue
            output = JsonConvert.DeserializeObject<T>(jsonString, settings);

            return output;
        }

        public static dynamic DeserializeFromJsonDynamic(string jsonString)
        {
            if (string.IsNullOrEmpty(jsonString))
                return default(dynamic);

            JsonSerializerSettings settings = new JsonSerializerSettings();

            dynamic output = JsonConvert.DeserializeObject(jsonString, settings);

            return output;
        }
    }
}
